package controllers;

import helpers.CrawlerHelper;
import helpers.FileHelper;
import helpers.IpHelper;
import helpers.StringHelper;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import debugs.IpAddressDebug;

import entities.IpAddress;

public class IpServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String ip = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (ip == null || ip.isEmpty()) {
			ip = request.getRemoteAddr();
		}
		
		IpAddress ipAddress = null;
		
		if (IpHelper.checkIsIp(ip)) {
			/*ipAddress = FileHelper.getByFileName(ip);
			if (ipAddress == null) {
				ipAddress = CrawlerHelper.getIp(ip);
				FileHelper.saveToObject(ipAddress);
			}*/
			
			ipAddress = CrawlerHelper.getIp(ip);
		}
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("ip", ip);
		request.setAttribute("ipAddress", ipAddress);
		try {
			request.getRequestDispatcher("/pages/ip.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
